import { Component, OnInit } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Subject, Observable } from "rxjs";
import { SignUpService } from "./sign-up.service";
import { FormGroup, FormBuilder, Validators } from "@angular/forms";
import { Router, ActivatedRoute } from "@angular/router";

@Component({
  selector: "app-sign-up",
  templateUrl: "./sign-up.component.html",
  styleUrls: ["./sign-up.component.scss"]
})
export class SignUpComponent implements OnInit {
  public userform: FormGroup;
  public userInfo: any = {};

  public formErrors = {
    email: "",
    password: "",
    confirmPassword: "",
    formError: "",
    vcode: ""
  };
  private validateionMessages = {
    email: {
      required: "邮箱必须输入",
      pattern: "请输入正确的地址"
    },
    password: {
      required: "密码必须输入",
      minlength: "密码至少要8位"
    },
    confirmPassword: {
      required: "重复密码必须输入",
      minlength: "密码至少要8位",
      validateEqual: "两次输入的密码不一致。"
    }
  };
  constructor(
    private fb: FormBuilder,
    private router: Router,
    private route: ActivatedRoute,
    private signUpService: SignUpService
  ) {}

  ngOnInit(): void {
    this.buildForm();
  }

  public buildForm(): void {
    this.userform = this.fb.group({
      email: [
        this.userInfo.email,
        [
          Validators.required,
          Validators.pattern(
            "^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$"
          )
        ]
      ],
      password: [
        this.userInfo.password,
        [Validators.required, Validators.minLength(8)]
      ],
      confirmPassword: [
        this.userInfo.confirmPassword,
        [Validators.required, Validators.minLength(8)]
      ]
    });
    this.userform.valueChanges.subscribe(data => this.onValueChanged(data));
    this.onValueChanged();
  }

  public onValueChanged(data?: any) {
    if (!this.userform) {
      return;
    }
    const form = this.userform;
    for (const field in this.formErrors) {
      this.formErrors[field] = "";
      const control = form.get(field);
      if (control && control.dirty && !control.valid) {
        const messages = this.validateionMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + " ";
        }
      }
    }
  }

  public doRegister() {
    if (this.userform.valid) {
      this.userInfo = this.userform.value;
      console.log("userinfo--", this.userInfo);
      this.signUpService.doRegister();
      this.router.navigateByUrl("home");
    } else {
      this.formErrors.formError = "存在不合法的输入项，请检查。";
    }
  }
}
